﻿using UnityEngine;
using System.Collections;

public class Grid {
    public static int W = 10;
    public static int H = 13;
    public static Element[,] Elements = null;

    public static void uncoverMines() {
        foreach ( Element elem in Elements ) {
            if ( elem.IsMine ) {
                elem.LoadTexture( 0 );
            }
        }
    }

    public static bool mineAt( int x, int y ) {
        return ( x >= 0 && y >= 0 && x < W && y < H ) ? Elements[x, y].IsMine : false;
    }

    public static int adjacentMines( int x, int y ) {
        int count = 0;

        if ( mineAt( x, y + 1 ) ) ++count;
        if ( mineAt( x + 1, y + 1 ) ) ++count;
        if ( mineAt( x + 1, y ) ) ++count;
        if ( mineAt( x + 1, y - 1 ) ) ++count;
        if ( mineAt( x, y - 1 ) ) ++count;
        if ( mineAt( x - 1, y - 1 ) ) ++count;
        if ( mineAt( x - 1, y ) ) ++count;
        if ( mineAt( x - 1, y + 1 ) ) ++count;

        return count;
    }

    //Flood Fill
    public static void FFuncover( int x, int y, bool[,] visited ) {
        if ( x >= 0 && y >= 0 && x < W && y < H ) {
            if ( visited[x, y] ) 
                return;
            visited[x, y] = true;
            int adjacentNum = adjacentMines( x, y );
            Elements[x, y].LoadTexture( adjacentNum );
            if ( adjacentNum > 0 ) 
                return;

            FFuncover( x - 1, y, visited );
            FFuncover( x + 1, y, visited );
            FFuncover( x, y + 1, visited );
            FFuncover( x, y - 1, visited );
            //FFuncover( x - 1, y - 1, visited );
            //FFuncover( x + 1, y - 1, visited );
            //FFuncover( x - 1, y + 1, visited );
            //FFuncover( x + 1, y + 1, visited );
        }
    }

    public static bool IsFinished() {
        foreach ( Element elem in Elements ) {
            if ( elem.isCovered() && !elem.IsMine )
                return false;
        }
        return true;
    }

    public static void SetWidthHight( int theW,int theH ) {
        W = theW;
        H = theH;
    }
}
